package com.smx.controller;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.smx.common.Message;
import com.smx.dao.UserDao;
import com.smx.enums.ResponseStatusEnum;
import com.smx.enums.RoleEnum;
import com.smx.model.entity.Admin;
import com.smx.model.entity.User;
import com.smx.model.vo.UserVo;
import com.smx.mvc.ResponseBody;
import com.smx.mvc.ResponseView;
import com.smx.service.AdminService;
import com.smx.service.UserService;
import com.smx.util.GenderUtil;
import com.smx.util.JsonUtil;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.jsp.JspFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author moses
 * @Date 2021/5/9
 **/
public class UserController {


    @ResponseView("/loginPage.do")
    public String loginPage(Servlet servlet, HttpServletRequest req, HttpServletResponse response) {
        return "login.jsp";
    }

    @ResponseBody("/login.do")
    public String login(Servlet servlet, HttpServletRequest req, HttpServletResponse response) {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String role = req.getParameter("role");

        Message msg = new Message();

        if (role.equals(RoleEnum.ADMIN.value())) {
            //管理员登陆
            Admin admin = AdminService.findAdmin(new Admin().setUsername(username).setPassword(password));
            if (null != admin) {
                msg.setCode(ResponseStatusEnum.SUCCESS.value());
                msg.setMsg(ResponseStatusEnum.SUCCESS.info());
                msg.setResult(admin);
            }

        } else if (role.equals(RoleEnum.USER.value())) {
            //用户登陆
            UserVo user = (UserVo) UserService.findUser(new User().setAccount(username).setPassword(password));
            if (null != user) {
                user.setGenderStr(GenderUtil.getGenderStr(user.getGender()));
                msg.setCode(ResponseStatusEnum.SUCCESS.value());
                msg.setMsg(ResponseStatusEnum.SUCCESS.info());
                msg.setResult(user);
                req.getSession().setAttribute("userInfo", user);
            }
        }
        return JsonUtil.toJSON(msg);
    }

    @ResponseBody("/uploadAvatar.do")
    public String uploadAvatar(Servlet servlet, HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {

        try {
            //初始化smartupload
            SmartUpload su = new SmartUpload();
            JspFactory factory = JspFactory.getDefaultFactory();
            PageContext pageContext = factory.getPageContext(servlet, req, response, null, true, 8192, true);
            su.initialize(pageContext);
            su.setCharset("utf-8");
            su.upload();

            //获取表单数据
            String id = su.getRequest().getParameter("id");
            String name = su.getRequest().getParameter("nickname");
            String gender = su.getRequest().getParameter("sex");
            String phone = su.getRequest().getParameter("cellphone");
            String email = su.getRequest().getParameter("email");
            String remarks = su.getRequest().getParameter("remarks");

            //根据id查询原本数据
            User user = UserService.findUserById(Integer.valueOf(id));
            user.setName(name);
            user.setGender(Integer.valueOf(gender));
            user.setPhone(phone);
            user.setEmail(email);
            user.setRemarks(remarks);

            //文件另取名存放本地
            File file = su.getFiles().getFile(0);
            if (file != null) {
                if (file.getFileExt().equals("png") || file.getFileExt().equals("jpg")) {
                    String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + file.getFileExt();
                    String url = "avatar/" + filename;
                    file.saveAs(url, SmartUpload.SAVE_VIRTUAL);
                    //文件路径存放数据库
                    user.setAvatar(url);
                }
            }

            //保存数据库
            int i = UserDao.updateUser(user);
            PrintWriter writer = response.getWriter();

            if (i > 0) {
                req.getSession().setAttribute("userInfo",user);
            }


        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        return "<script>window.parent.location.reload();</script>";

    }
}
